package main

import (
	"fmt"
	lua "github.com/yuin/gopher-lua"
	"strconv"
	"strings"
)

func lua_expression(scriptstr string, info []uint16) float32 {
	L := lua.NewState()
	defer L.Close()
	//str := `ADDR_0X1800 ==180 and 1 or 0`
	i2 := strings.Split(scriptstr, " ")
	for _, s := range i2 {
		strings.ToUpper(s)
		contains := strings.Contains(s, "ADDR_")
		if contains == true {
			all := strings.ReplaceAll(s, "ADDR_", "")
			b := strings.Contains(all, "0X")
			if b == true {
				replaceAll := strings.ReplaceAll(all, "0X", "")
				i, _ := strconv.ParseInt(replaceAll, 16, 32)
				sprintf := fmt.Sprintf(`%v = %v;`, s, info[i])
				L.DoString(sprintf)
			} else {
				i, _ := strconv.ParseInt(all, 10, 32)
				sprintf := fmt.Sprintf(`%v = %v;`, s, info[i])
				L.DoString(sprintf)
			}
		}
	}

	sprintf := fmt.Sprintf(`%v %v;`, "ret = ", scriptstr)
	L.DoString(sprintf)
	L.DoString(`return ret;`)
	// 获取返回值
	if sum := L.GetTop(); sum > 0 {
		for i := 1; i <= sum; i++ {
			switch val := L.Get(-i).(type) {
			case lua.LString:
				return 0
			case lua.LNumber:
				return (float32(val))
			default:
				fmt.Printf("Unhandled type: %T\n", val)
			}
		}
	}
	return 0
}

func main2() {
	info := [65530]uint16{}
	info[6144] = 8
	infos := info[:]
	expression := lua_expression(" band ( 0x1  , 0x3 )  ", infos)
	fmt.Println(expression)
}
